const express = require("express");
const moment = require('moment')
const {parse} = require('url')
const bodyParser = require("body-parser");
const cors = require('cors');
const app = express();

app.use(cors());
// app.use((req, res, next) => {
//     console.log('app.use  req,',req); // 打印请求体
//     next();
//   });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const genList = (current, pageSize) => {
  const tableListDataSource = [];

  for (let i = 0; i < pageSize; i += 1) {
    const creators = ["付小小", "曲丽丽", "林东东", "陈帅帅", "兼某某"];
    const roles = [["老师", "管理员"], "学生", ["老师", "家长"]];
    const classes = [["一年级2班", "二年级1班"], "一年级1班"];
    const index = (current - 1) * 10 + i;
    let classRandom = classes[Math.floor(Math.random() * classes.length)];
    let roleRandom = roles[Math.floor(Math.random() * roles.length)];
    tableListDataSource.push({
      key: index,
      name: creators[Math.floor(Math.random() * creators.length)],
      phoneNumber: "13112345678",
      class: (classRandom =
        typeof classRandom === "string" ? classRandom : classRandom.join("、")),
      roles: (roleRandom =
        typeof roleRandom === "string" ? roleRandom : roleRandom.join("、")),
      updatedAt: moment().format("YYYY-MM-DD"),
      createdAt: moment().format("YYYY-MM-DD"),
    });
  }
  tableListDataSource.reverse();
  return tableListDataSource;
};

let tableListDataSource = genList(1, 100);

function getRule(req, res, u) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
      realUrl = req.url;
    }
    const { current = 1, pageSize = 10 } = req.query;
    const params = parse(realUrl, true).query

    let dataSource = [...tableListDataSource].slice(
      ((current) - 1) * (pageSize),
      (current) * (pageSize),
    );
    if (params.sorter) {
      const sorter = JSON.parse(params.sorter);
      dataSource = dataSource.sort((prev, next) => {
        let sortNumber = 0;
        Object.keys(sorter).forEach((key) => {
          if (sorter[key] === 'descend') {
            if (prev[key] - next[key] > 0) {
              sortNumber += -1;
            } else {
              sortNumber += 1;
            }
            return;
          }
          if (prev[key] - next[key] > 0) {
            sortNumber += 1;
          } else {
            sortNumber += -1;
          }
        });
        return sortNumber;
      });
    }
    if (params.filter) {
      const filter = JSON.parse(params.filter)
      if (Object.keys(filter).length > 0) {
        dataSource = dataSource.filter((item) => {
          return Object.keys(filter).some((key) => {
            if (!filter[key]) {
              return true;
            }
            if (filter[key].includes(`${item[key]}`)) {
              return true;
            }
            return false;
          });
        });
      }
    }

    if (params.name) {
      dataSource = dataSource.filter((data) => data?.name?.includes(params.name || ''));
    }
    const result = {
      data: dataSource,
      total: tableListDataSource.length,
      success: true,
      pageSize,
      current: parseInt(`${params.current}`, 10) || 1,
    };

    return res.json(result);
}

function postRule(req, res, u, b) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
      realUrl = req.url;
    }
    const body = (b && b.body) || req.body;
    const { method, name, phoneNumber, key, roles } = body;
    console.log(method);

    switch (method) {
      /* eslint no-case-declarations:0 */
      case 'delete':
        tableListDataSource = tableListDataSource.filter((item) => key.indexOf(item.key) === -1);
        break;
      case 'post':
        (() => {
          const newRule = {
            key: tableListDataSource.length,
            phoneNumber,
            name,
            roles,
            class: '1年级',
            updatedAt: moment().format('YYYY-MM-DD'),
            createdAt: moment().format('YYYY-MM-DD'),
          };
          tableListDataSource.unshift(newRule);
          return res.json(newRule);
        })();
        return;

      case 'update':
        (() => {
          let newRule = {};
          console.log(name);
          tableListDataSource = tableListDataSource.map((item) => {
            if (item.key === key) {
              newRule = { ...item, name, phoneNumber };
              return { ...item, name, phoneNumber };
            }
            return item;
          });
          console.log('newRule', newRule);
          return res.json(newRule);
        })();
        return;
      default:
        break;
    }

    const result = {
      list: tableListDataSource,
      pagination: {
        total: tableListDataSource.length,
      },
    };

    res.json(result);
  }

app.get("/api/usercenter", (req, res) => {
    getRule(req, res, req.url)
});

app.post("/api/usercenter", (req, res) => {
  postRule(req, res)
});

// app.listen(3000, () => {
//   console.log("Server started on port 7002");
// });
